package com.quo.controller;

import com.order.hit.crossover.platform.common.bean.Notice;
import com.order.hit.crossover.platform.common.bean.order.OrderState;
import com.order.hit.crossover.platform.common.bean.order.Quotation;
import com.order.hit.crossover.platform.common.dao.QuotationDao;
import com.order.hit.crossover.platform.common.utils.PFResponse;
import com.quo.service.QuotationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

/**
 * @author Lei
 * @version 0.1
 * @date 2020/8/6
 */
@RestController
@RequestMapping("/quotationService")
public class QuotationController {

    @Autowired
    @Qualifier("QuotationServiceImpl")
    private QuotationService quotationService;

    @PostMapping("/addQuotation")
    public PFResponse addQuotation(@RequestBody QuotationDao quotationDao){
        quotationDao.setQuotationId(UUID.randomUUID().toString().substring(24));
        int code = 0;
        String message = "";
        try{
            this.quotationService.add(quotationDao);
            code = 200;
            message = "添加成功";
        }catch (Exception e){
            e.printStackTrace();
            code = 500;
            message = "添加失败";
        }
        return new PFResponse().code(code).message(message);
    }

    //删除报价单
    @DeleteMapping("/deleteQuation/{id}")
    public PFResponse deleteQuotation(@PathVariable("id")String id){
        int code = 0;
        String message = "";
        try{
            this.quotationService.deletebyId(id);
            code = 200;
            message = "删除成功";
        }catch (Exception e){
            code = 500;
            message = "删除失败";
        }
        return new PFResponse().message(message).code(code);
    }


    @PutMapping("/updateQuo")
    public PFResponse updateQuo(@RequestBody QuotationDao quotationDao){
        int code = 0;
        String message = "";
        try{
            this.quotationService.update(quotationDao);
            code = 200;
            message = "更新成功";
        }catch (Exception e){
            code = 500;
            message = "更新失败";
        }
        return new PFResponse().message(message).code(code);
    }

    //得到某一个订单的详细信息
    @GetMapping("/getQuotionByQuotionId/{id}")
    public PFResponse getQuotionByQuotionId(@PathVariable("id")String id){
        PFResponse pfResponse= new PFResponse();
        Quotation quotation = this.quotationService.selectById(id);
        pfResponse.code(200);
        pfResponse.data(quotation);
        return pfResponse;
    }

    // 得到针对某一个订单的所有报价单
    @GetMapping("getQuotionByOrderId/{id}")
    public PFResponse getQuotionByOrderId(@PathVariable("id")String id){
        PFResponse p = new PFResponse();
        List<Quotation> list = this.quotationService.selectByOrderId(id);
        p.code(200);
        p.data(list);
        return p;
    }

    // 得到针对某一个订单的所有报价单,没超时间的
    @GetMapping("getQuotionByOrderIdInTime/{id}")
    public PFResponse getQuotionByOrderIdInTime(@PathVariable("id")String id){
        PFResponse p = new PFResponse();
        List<Quotation> list = this.quotationService.selectByOrderId(id);
        Iterator<Quotation> iterable = list.iterator();
        while (iterable.hasNext()){
            if(!iterable.next().getQuotationState().equals(OrderState.QUOTATION_DISPLAY)){
                iterable.remove();
            }
        }
        p.code(200);
        p.data(list);
        return p;
    }

    // 得到针对某一个订单的所有报价单的商店id
    @GetMapping("getQuotionsStoreIdByOrderId/{id}")
    public PFResponse getQuotionIdByOrderId(@PathVariable("id")String id){
        PFResponse p = new PFResponse();
        List<Quotation> list = this.quotationService.selectByOrderId(id);
        List<String> result = new ArrayList<>(list.size());
        for (Quotation quotation: list){
            result.add(quotation.getStore().getStoreId());
        }
        p.code(200);
        p.data(result);
        return p;
    }

    // 按某种策略策略进行排序 策略0表示价格排序，策略1表示位置排序，策略2表示有效期至,策略3表示相关性,策略4表示符合预期价格的
    @GetMapping("getQuotionByOrderIdAndCe")
    public PFResponse getQuotionByOrderIdAndsta(@RequestParam("id")String id, @RequestParam("strategy")int strategy){
        PFResponse p = new PFResponse();
        List<Quotation> list = this.quotationService.selectByOrderIdAndstrategy(id, strategy);
        // 只给出正在展示的
        Iterator<Quotation> iterable = list.iterator();
        while (iterable.hasNext()){
            if(!iterable.next().getQuotationState().equals(OrderState.QUOTATION_DISPLAY)){
                iterable.remove();
            }
        }

        p.code(200);
        p.data(list);
        return p;
    }


    // 更新订单状态
    @PutMapping("updateQuotionState")
    public PFResponse updateQuotionState(@RequestParam("id")String id, @RequestParam("state")String state, @RequestParam("storeId")String storeId){
        int code = 0;
        String message = "";
        try{
            Quotation q = this.quotationService.selectById(id);
            q.setQuotationState(OrderState.valueOf(state.toUpperCase()));
            this.quotationService.update(QuotationDao.getQuatationDao(q));
            //  生成通知信息
            String success_info1 = "您的订单(" + q.getGood().getGoodName() + ")已成交， 请前往本店求购/求售查看。";
            Notice success_notice1 = new Notice(success_info1,0,0,storeId);
            new RestTemplate().exchange("http://notice:18083/Notice/add", HttpMethod.POST, new HttpEntity<>(success_notice1, new HttpHeaders()), PFResponse.class);
            String success_info2 = "您的报价单(" + q.getGood().getGoodName() + ")已成交， 请前往报价单购买/出售查看。";
            Notice success_notice2 = new Notice(success_info2,0,0,q.getStore().getStoreId());
            new RestTemplate().exchange("http://notice:18083/Notice/add", HttpMethod.POST, new HttpEntity<>(success_notice2, new HttpHeaders()), PFResponse.class);
            if (state.equalsIgnoreCase(OrderState.QUOTATION_ACCEPT.toString())){
                // 其余没有超时得报价单需要更改为 未被接受得状态
                List<Quotation> list = this.quotationService.selectByOrderId(q.getOrderId());
                for(Quotation quotation: list){
                    if(quotation.getQuotationState().equals(OrderState.QUOTATION_DISPLAY)){
                        quotation.setQuotationState(OrderState.QUOTATION_NOT_ACCEPT);
                        this.quotationService.update(QuotationDao.getQuatationDao(quotation));

                        //  生成通知信息
                        String fail_info = "您的报价单(" + quotation.getGood().getGoodName() + ")已失败， 请前往报价单购买/出售查看。";
                        Notice fail_notice = new Notice(fail_info,0,0,quotation.getStore().getStoreId());
                        new RestTemplate().exchange("http://notice:18083/Notice/add", HttpMethod.POST, new HttpEntity<>(fail_notice, new HttpHeaders()), PFResponse.class);
                    }
                }
            }
            code = 200;
            message = "状态更新成功";
        }catch (Exception e){
            code = 500;
            message = "状态更新失败";
            e.printStackTrace();
        }
        return new PFResponse().message(message).code(code);
    }

    /**
     *
     * @param storeId
     * @return QUOTATION_BUY
     */
    @GetMapping("/getStoresQuoOfBuy/{storeId}")
    public PFResponse getStoresQuoOfBuy(@PathVariable("storeId")String storeId){
        List<Quotation> list = this.quotationService.selectBuyOfStore(storeId);
        return new PFResponse().data(list).code(200);
    }

    /**
     *
     * @param storeId
     * @return 出售报价
     */
    @GetMapping("/getStoresQuoOfSold/{storeId}")
    public PFResponse getStoresQuoOfSold(@PathVariable("storeId")String storeId){
        List<Quotation> list = this.quotationService.selectSoldOfStore(storeId);
        return new PFResponse().data(list).code(200);
    }


    /**
     * 得到success状态的订单的 报价单
     * @param orderId
     * @return
     */
    @GetMapping("/getSuccessOrdersQua/{orderId}")
    public PFResponse getSuccessOrdersQua(@PathVariable("orderId")String orderId){
        Quotation quotation = this.quotationService.getSuccessQuo(orderId);
        return quotation == null?new PFResponse().data(null).code(400).message("查询失败"):new PFResponse().data(quotation).code(200);
    }


    @GetMapping("/getQuoByOrderId/{quoId}")
    public PFResponse getOrderIdByQuoId(@PathVariable("quoId")String quoId){
        return new PFResponse().data(this.quotationService.getOrderByquoId(quoId)).code(200);
    }
}
